import preferences from '@ohos.data.preferences';

const PREF_NAME = 'app_settings';
const KEY_FONT_SIZE = 'font_size';
const KEY_TEXT_COLOR = 'text_color';
const DEFAULT_FONT_SIZE = 16;
const DEFAULT_TEXT_COLOR = '#000000';

class PreferencesUtil {
  private pref: preferences.Preferences | null = null;

  async initPreferences(): Promise<void> {
    try {
      this.pref = await preferences.getPreferences(globalThis.context, PREF_NAME);
    } catch (err) {
      console.error(`Preferences init failed: ${err.code} ${err.message}`);
    }
  }

  // 明确指定返回类型为 number
  async getFontSize(): Promise<number> {
    if (!this.pref) await this.initPreferences();
    try {
      const size = await this.pref.get(KEY_FONT_SIZE, DEFAULT_FONT_SIZE);
      // 确保返回的是 number 类型
      return typeof size === 'number' ? size : DEFAULT_FONT_SIZE;
    } catch (err) {
      return DEFAULT_FONT_SIZE;
    }
  }

  // 明确参数类型为 number
  async saveFontSize(size: number): Promise<void> {
    if (!this.pref) await this.initPreferences();
    try {
      await this.pref.put(KEY_FONT_SIZE, size);
      await this.pref.flush();
    } catch (err) {
      console.error(`Save font size failed: ${err.code} ${err.message}`);
    }
  }

  // 明确指定返回类型为 string
  async getTextColor(): Promise<string> {
    if (!this.pref) await this.initPreferences();
    try {
      const color = await this.pref.get(KEY_TEXT_COLOR, DEFAULT_TEXT_COLOR);
      // 确保返回的是 string 类型
      return typeof color === 'string' ? color : DEFAULT_TEXT_COLOR;
    } catch (err) {
      return DEFAULT_TEXT_COLOR;
    }
  }

  // 明确参数类型为 string
  async saveTextColor(color: string): Promise<void> {
    if (!this.pref) await this.initPreferences();
    try {
      await this.pref.put(KEY_TEXT_COLOR, color);
      await this.pref.flush();
    } catch (err) {
      console.error(`Save text color failed: ${err.code} ${err.message}`);
    }
  }
}

export const prefUtil = new PreferencesUtil();